﻿/*
    Copyright (c) 2011, Jeremy Randall (http://www.auburnrandall.com)
      
    All rights reserved.
 
    Redistribution and use in source and binary forms, with or without
    modification, are permitted provided that the following conditions are met:
 
    1. Redistributions of source code must retain the above copyright notice,
    this list of conditions and the following disclaimer.
 
    2. Redistributions in binary form must reproduce the above copyright 
    notice, this list of conditions and the following disclaimer in 
    the documentation and/or other materials provided with the distribution.
 
    3. The names of the authors may not be used to endorse or promote products
    derived from this software without specific prior written permission.
 
    THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESSED OR IMPLIED WARRANTIES,
    INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
    FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR
    OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
    INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
    LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
    OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
    LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
    NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
    EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

using System;
using System.Collections.Generic;
using System.Xml.Serialization;

namespace FormEngine
{
    /// <summary>
    /// Representation of an individual that is associated with Forms.
    /// </summary>
    public class FormUser
    {
        public FormUser()
        {
            Username = string.Empty;
            FormsOwned = new List<string>();
            LicenseCount = 1; // freebie
            LicenseExpiration = DateTime.Today;
        }

        /// <summary>
        /// Unique identifier for user. Should match Identity.Name property.
        /// </summary>
        [XmlAttribute("username")]
        public string Username { get; set; }

        /// <summary>
        /// The number of forms the user can license.
        /// </summary>
        [XmlAttribute("licenseCount")]
        public int LicenseCount { get; set; }

        /// <summary>
        /// Date the current license expires.
        /// </summary>
        [XmlAttribute("licenseExpiration")]
        public DateTime LicenseExpiration { get; set; }

        /// <summary>
        /// Internal list that is used to serialize the form data.
        /// </summary>
        public List<string> FormsOwned { get; set; }

        /// <summary>
        /// Inidicates if the user will be required to purchase more
        /// licenses.
        /// </summary>
        public bool InsufficientLicenses
        {
            get
            {
                if (FormsOwned.Count > LicenseCount)
                {
                    return true;
                }

                return false;
            }
        }

        /// <summary>
        /// Load specified form user from data source.
        /// </summary>
        /// <param name="username">User that will be retrieved.</param>
        /// <returns>Instance of FormUser</returns>
        public static FormUser Load(string username)
        {
            FormUser user = FormDataProvider.Instance.GetUser(username);

            if (user == null)
            {
                user = new FormUser() { Username = username };
            }

            return user;
        }

        /// <summary>
        /// Saves the current FormUser instance.
        /// </summary>
        public void Save()
        {
            FormDataProvider.Instance.SaveUser(this);
        }

        /// <summary>
        /// Returns the user's current list of associated forms.
        /// </summary>
        /// <returns>Array of forms</returns>
        public FormProperties[] GetForms()
        {
            FormPropertiesCollection list = new FormPropertiesCollection();

            foreach (string formid in FormsOwned)
            {
                list.Add(FormProperties.Load(formid));
            }

            return list.ToArray();
        }

        /// <summary>
        /// Adds referenced form to user's Forms collection. Will set the appropriate
        /// expiration for the form.
        /// </summary>
        /// <param name="form">Form that will be added</param>
        internal void AddForm(FormProperties form)
        {
            if (!FormsOwned.Contains(form.FormId))
            {
                FormsOwned.Add(form.FormId);

                DateTime expdate = DateTime.Today.AddDays(30);

                if (FormsOwned.Count == 1)
                {
                    form.ExpirationDate = DateTime.MaxValue;
                }
                else if (FormsOwned.Count <= LicenseCount && LicenseExpiration > expdate)
                {
                    // added forms will always get at least 30 days.
                    form.ExpirationDate = LicenseExpiration;
                }
                else
                {
                    form.ExpirationDate = DateTime.Today.AddDays(30);
                }
            }

            Save();
        }

        /// <summary>
        /// Removes form from user's Forms collection.
        /// </summary>
        /// <param name="form">Form that will be removed.</param>
        public void RemoveForm(FormProperties form)
        {
            if (FormsOwned.Contains(form.FormId))
            {
                FormsOwned.Remove(form.FormId);
            }

            Save();

            form.Delete();

            LicenseForms();
        }

        /// <summary>
        /// Adjusts the expiration date for the forms associated with this user.
        /// </summary>
        public void LicenseForms()
        {
            DateTime expdate = DateTime.Today.AddDays(30);
            FormProperties[] forms = GetForms();

            for (int i = 0; i < forms.Length; i++)
            {
                if (i == 0)
                {
                    forms[i].ExpirationDate = DateTime.MaxValue;
                }
                else if (i < LicenseCount)
                {
                    forms[i].ExpirationDate = LicenseExpiration;
                }
                else
                {
                    // Was previously set to future date but there isn't a license for
                    // it. This is now an unlicensed form.
                    if (forms[i].ExpirationDate > expdate)
                    {
                        forms[i].ExpirationDate = expdate;
                    }

                    // if the form expiration is within the month, don't reset
                    // with grace period.
                }
            }
        }
    }
}
